// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

package clientserver; 
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import clientserver.Packet.PacketType;

import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.ResultSetMetaData;


import clientserver.ocsf.*;


public class Server extends AbstractServer 
{
  //Class variables *************************************************
  
  /**
   * The default port to listen on.
   */
Connection conn;
String login;
String password;
String sql;
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the echo server.
   *
   * @param port The port number to connect on.
   */
  public Server(int port, String dblogin, String dbpassword,String sqlIP) 
  {
    super(port);
    login=dblogin;
    password=dbpassword;
  sql=sqlIP;   
  }

 //MYSQL work methods*****************************************************
  public  void connectToMySQL()
  {
  	try 
  	{
          Class.forName("com.mysql.jdbc.Driver").newInstance();
      } catch (Exception ex) {/* handle the error*/}
      
      try 
      {
    	  //"jdbc:mysql://localhost/ICM"
       conn = (Connection) DriverManager.getConnection("jdbc:mysql://"+sql+"/ICM", login,password);
          System.out.println("SQL connection succeed");


   	}
      
      catch (SQLException ex) 
   	    {/* handle any errors*/
          System.out.println("SQLException: " + ex.getMessage());
          System.out.println("SQLState: " + ex.getSQLState());
          System.out.println("VendorError: " + ex.getErrorCode());
          }
  
  } 
  private ResultSet ExecuteQuery( String q) throws Exception 
  {
  	java.sql.Statement stmt=null;
  	ResultSet rs=null;

  		
			stmt = conn.createStatement();
		
  		
  		
		rs = (ResultSet) stmt.executeQuery(q);
	
  	
  	return rs;
  	
  }
  
  private void RunDBupdate( String q) throws Exception 
  {
  	java.sql.Statement stmt=null;
  	ResultSet rs=null;

  		
			stmt = conn.createStatement();
		
  		

		 stmt.executeUpdate(q);
	

  	
  }
  
  
  
  //Instance methods ************************************************
  
  /**
   * This method handles any messages received from the client.
   *
   * @param msg The message received from the client.
   * @param client The connection from which the message originated.
 * @throws Exception 
   */
public void handleMessageFromClient(Object o, ConnectionToClient client) throws Exception
  {
	Packet p=(Packet) o;

		
	ResultSet rs;
	
	switch(p.type)  
	{	
	case SELECT:// then Server answer will be Query Result Object

	 String smsg=(String) p.data;
			rs = ExecuteQuery(smsg);
		
			QueryResult answer=new QueryResult(rs);
				client.sendToClient(answer);
	break;	
	case UPDATE :   // no server answer in this case
		 String umsg=(String) p.data;
		 RunDBupdate(umsg); break;
		
	case SAVEFILE:
		AttachedFile file=(AttachedFile) p.data;
		 file.onserverside();
		file.savefile();
		break;
	case GETFILE:  AttachedFile rfile=(AttachedFile) p.data;
	rfile.onserverside();
	rfile.loadfile();
	client.sendToClient(rfile);
		
		break;	
	case GETDATE: 
		
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		Date date = new Date();
		String currdate=dateFormat.format(date);
		client.sendToClient(currdate);
		
					
		
	
	
	} //switch end	
		
		
	
	

	

	


    
	 
	    }   //handlemessagefromclient

    
  /**
   * This method overrides the one in the superclass.  Called
   * when the server starts listening for connections.
   */
  protected void serverStarted()
  {
    System.out.println("Server listening for connections on port " + getPort());
  }
  
  /**
   * This method overrides the one in the superclass.  Called
   * when the server stops listening for connections.
   */
  protected void serverStopped()
  {
    System.out.println("Server has stopped listening for connections.");
  }
  
  //Class methods ***************************************************
  
  /**
   * This method is responsible for the creation of 
   * the server instance (there is no UI in this phase).
   *
   * @param args[0] The port number to listen on.  Defaults to 5555 
   *          if no argument is entered.
 * @throws UnknownHostException 
   */
 
  
  public static void main(String[] args) 
  {
    String host = "localhost";
    int port = 1234;  //The port number


   Server sr= new Server(port,"root","Braude","localhost");
   sr.connectToMySQL();
    try {
		sr.listen();
	}
    
    
    catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}  


  
  }
  
  }

//End of EchoServer class
